/**
 * Created by lwy on 2017/8/30.
 */


var details;
var ifSpeImg = 'false';
var fenqiId;
var  specificationName,
    prepayment,
    periods,
    instalmentAmount,
    goodsName,
    fenqiState;

$(function () {
    var id= $('#idBox').html();
    getCrmDetails(id);
})

function getCrmDetails(id){
    $.ajax({
        url: '/crm/ddmGoodsC/getCrmDetails.json',
        dataType: 'json',
        data: {
            token: localStorage.getItem('crmtoken'),
            id: id,
        },
        success: function (data) {
            if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            }
            if (data.code == 0) {
                alert(data.msg);
            }
            if (data.code == 1) {
                var data = data.datas;
                $('#name').val(data.name);
                $('#sumary').val(data.abbreviation);
                $('#goodsExplain').val(data.goodsExplain);
                $('#purchasePrice').val(data.purchasePrice);
                $('#memberPrice').val(data.memberPrice);
                $('#ddPrice').val(data.ddPrice);
                $('#costPrice').val(data.costPrice);
                $('#addstate').val(data.goodsState);
                var morePic = data.mainImg.split(',');
                console.log(morePic.length);
                $('#imgBox').empty();
                if(morePic.length>1){
                    for(var i=0;i<morePic.length-1;i++){
                        $('<div class="oneImgBox"><img src="'+morePic[i]+'" ifShow="true"/><span>×</span></div>').appendTo($('#imgBox'))
                    }
                }else{
                    $('<div class="oneImgBox"><img src="'+morePic[0]+'" ifShow="true"/><span>×</span></div>').appendTo($('#imgBox'))
                }
                $('.oneImgBox span').click(function () {
                    $(this).parent().empty().hide();
                })
                //$('#mainImg').attr('src', data.mainImg);
                var details = data.details;
                var ue = UE.getEditor('container', {
                    autoHeight: false,
                    initialFrameHeight:800
                });
                ue.addListener("ready",function(){
                    // editor准备好之后才可以使用  
                    ue.setContent(data.details);

                });
                $('#keyWord').val(data.keyWord);
                $('#safeguard').find('div[contenteditable="true"]').html(data.safeguard);
                $('#parameter').find('div[contenteditable="true"]').html(data.parameter);
                if (data.isWarranty == '保修') {
                    $('#ifCash').val('是');
                    $('#deliveryArea').show();
                } else {
                    $('#ifCash').val('否');
                    $('#deliveryArea').hide();
                }
                $('#warrantyPeriod').val(data.warrantyPeriod);
                details = data.detailsImg;
                $('#detailImg img').load(function () {
                    $('#detailImg img').css({'width': '40px', 'height': '40px', 'margin-right': '10px'})
                })
                if (data.state == "有效") {
                    $('#xiajia').show();
                    $('#shangjia').hide();
                }
                if (data.state == '无效') {
                    $('#shangjia').show();
                    $('#xiajia').hide();
                }
                //点击放大图片
                $('#mainImg,#detailImg img').click(function () {
                    var src = $(this).attr('src');
                    $('#bigImg').attr('src', src);
                    $('#closeImg').show();
                })
                $('#closeImg,#close2').click(function () {
                    $('#closeImg').hide();
                })
            }
        }
    })

}
$('#isWarranty').change(function () {
    if ($(this).val() == "false") {
        $('#deliveryArea').hide();
    } else {
        $('#deliveryArea').show();
    }
})

$(document).on('click','.oneImgBox span',function () {
    $(this).parent().empty().hide();
})

$('#isWarranty').focus(function () {
    $('#ifCashText1').show();
})
$('#scope').focus(function () {
    $('#scopeText').show();
})


/*sfy
*规格展示函数
* */
function ggzs() {

    $.ajax({
        type: 'POST',
        url: '/crm/specificationC/getSpecificationAll.json?v=' + new Date().getTime(),
        dataType: "json",   //参数格式为json
        data: {
            goodid: $('#idBox').html()
        },
        success: function (data) {
            if (data.code == 0) {
                alert(data.msg);
            } else if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            } else if (data.code == 1) {
                $('#guigetable').empty();
                //将商品的规格内容铺进去
                $.each(data.datas, function (index, obj) {
                    var tdName = $("<tr><td>" + obj.name + "</td>");
                    tdName.append($("<td>" + obj.isValid + "</td>"))
                    tdName.append($("<td>" + obj.createTime + "</td>"));
                    tdName.append($("<td><a onclick='aa(this)' id=" + obj.id + ">编辑</a></td></tr>"));
                    $('#guigetable').append(tdName);
                });
            }

        }
    });

}

/*
* 请求商品的规格并且展示在页面上面
* */
ggzs();


//上传主图
var mainImg;
$('#avatarInput').on('change', function (e) {
    var filemaxsize = 1024 * 5;//5M
    var target = $(e.target);
    var Size = target[0].files[0].size / 1024;
    if (Size > filemaxsize) {
        alert('图片过大，请重新选择!');
        $(".avatar-wrapper").childre().remove;
        return false;
    }
    if (!this.files[0].type.match(/image.*/)) {
        alert('请选择正确的图片!')
    } else {
        var filename = document.querySelector("#avatar-name");
        var texts = document.querySelector("#avatarInput").value;
        var teststr = texts; //你这里的路径写错了
        testend = teststr.match(/[^\\]+\.[^\(]+/i); //直接完整文件名的
        filename.innerHTML = testend;
    }

});


$(".avatar-save").on("click", function () {
    var img_lg = document.getElementById('imageHead');
    // 截图小的显示框内的内容
    html2canvas(img_lg, {
        allowTaint: true,
        taintTest: false,
        onrendered: function (canvas) {
            canvas.id = "mycanvas";
            //生成base64图片数据
            var dataUrl = canvas.toDataURL("image/jpeg");
            var newImg = document.createElement("img");
            newImg.src = dataUrl;
            imagesAjax(dataUrl)
        }
    });
})

//保存修改
$('#save').click(function () {
    if ($('#avatar-name').html() == "") {
        alert('请选择图片');
    } else {
        $('#save').attr('data-dismiss', 'modal')
    }
})

function imagesAjax(src) {
    var data = {};
    data.img = src;
    data.jid = $('#jid').val();
    mainImg = src;

    $.ajax({
        url: '/crm/image/uploadImage.json',
        data: {
            filed: mainImg,
        },
        dataType: 'json',
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                //$('#mainImg').show();
                $('#mainImg').attr('src', data.datas.path);
                //$('#update').html('更换')
            }
        }
    })
}

var imgs = "";
var IMG = 0;
var IMG2 = 0;
var yuanImg = '';

function changeImg() {
    selectOver2();
}

function selectOver2() {
    IMG2++;
    $.ajaxFileUpload({
        url: '/crm/uploadImage.do?isDetail=true',
        type: 'POST',
        fileElementId: 'imageUpload',
        dataType: 'JSON',
        success: function (data) {
            var results = data.split('|');
            var flag = results[0].split('>');
            if (flag[1] != 'success') {
                mui.alert('上传失败');
                IMG2--;
                return;
            }
            var img = results[1].substring(results[1].length - 6, 0);
            if (yuanImg == "") {
                yuanImg = img;
            } else {
                yuanImg = yuanImg + ',' + img;
            }

            var imgLength = yuanImg.split(',');
            var imgHtml = '';
            for (var i = 0; i < imgLength.length; i++) {
                imgHtml += '<img src="' + imgLength[i] + '" alt="img" style="width: 90%"/>'
            }
            $('#target').val(imgHtml);
            $('#content').html(imgHtml);


        },
        error: function (data) {
            IMG2--;
            mui.alert('上传失败');

        }
    })
}

//更改商品详情
$('.editDetail').click(function () {
    $('#detailBox').show();
    $('#content').html(details);
    $('#target').val(details);
})

//修改
$('#editAll').click(function () {
    $('#editAll').hide();
    $('#detailBox').show();
    $('#content').html(details);
    $('#target').val(details);
    $('input').removeAttr('readonly');
    $('#inventory').attr('readonly', true);
    $('#ifCash').hide();
    $('#ifCashSelect').show();
    $('#delivery').hide();
    $('#clock').show();
    $('#update').show();
    //$('#save').show();
    $('#save2').show();

})

//保存修改
$('#save2').click(function () {
    var mainImg = '';
    // if ($('#mainImg').attr('src') == '../static/img/uploadImg.png') {
    //     mainImg = '';
    // } else {
    //     mainImg = $('#mainImg').attr('src');
    // }
    $(".oneImgBox img[ifShow=true]").each(function(i){
        mainImg+=$(this).attr("src")+","
    });
    if(mainImg=="../static/img/uploadImg.png"){
        mainImg='';
    }

    console.log(mainImg);
    var ue2 = UE.getEditor('container', {
        autoHeight: false,
        initialFrameHeight:800
    });

    function getContent() {
        var html = ue2.getContent();
        return html;
    }
    var details  = getContent();
    $.ajax({
        url: '/crm/ddmGoodsC/goodsModification.json',
        dataType: 'json',
        data: {
            abbreviation: $('#sumary').val(),
            name: $('#name').val(),
            mainImg: mainImg,
            goodsExplain: $('#goodsExplain').val(),
            purchasePrice:$('#purchasePrice').val(),
            costPrice:$('#costPrice').val(),
            ddPrice:$('#ddPrice').val(),
            memberPrice:$('#memberPrice').val(),
            isWarranty:$('#isWarranty').val(),
            warrantyPeriod:$('#warrantyPeriod').val(),
            isImie:$('#isImie').val(),
            parameter: $('#parameter').find('div[contenteditable="true"]').html(),
            safeguard:$('#safeguard').find('div[contenteditable="true"]').html(),
            detailsImg: details,
            id: $('#idBox').html(),
            token: localStorage.getItem('crmtoken'),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 0) {
                alert(data.msg);
            }
            if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp"
            }
            if (data.code == 1) {
                alert('修改申请成功')
            }
        }
    })
})


var payMoney2 = 0.00;


//规格信息
var sContent1 = '';
var sContent2 = '';
//判断是否已有规格（有几个规格）
var hasSpe;
$(function () {
    $.ajax({
        url: '/crm/specificationC/getSpecificationAll.json',
        dataType: 'json',
        data: {
            goodid: $('#idBox').html(),
        },
        type: 'post',
        success: function (data) {
            if (data.datas.length == 0) {
                hasSpe = 0;
                $('#specificationName1').show();
                $('#specifcationContentName1').show();
                $('#specificationName2').show();
                $('#specifcationContentName2').show();
                $('#addSpe').show();
                $('#editSpe').hide();
            } else if (data.datas.length == 1) {
                hasSpe = 1;
                $('#specificationName1').show();
                $('#specifcationContentName1').show();
                $('#specificationName2').hide();
                $('#specifcationContentName2').hide();
                $('#specificationName3').show();
                $('#specifcationContentName3').show();
                $('#specificationName4').hide();
                $('#specifcationContentName4').hide();
                $('#addSpe').show();
                $('#editSpe').show();
                $.ajax({
                    url: '/crm/specificationC/getSpecificationAndContent.json',
                    dataType: 'json',
                    data: {
                        goodid: $('#idBox').html(),
                    },
                    type: 'post',
                    success: function (data) {
                        if (data.code == 1) {
                            $('<div style="position: relative;width: 165px;"><input class="db_input bigSpe specificationName3" type="text" value="' + data.datas[0].name + '" id="' + data.datas[0].id + '"></div>').appendTo($('#spe_title1'));
                            for (var b = 0; b < data.datas[0].data.length; b++) {
                                $('<div style="float: left;position: relative;"><input class="db_input" type="text" readonly value="' + data.datas[0].data[b].content + '" id="' + data.datas[0].data[b].id + '"></div>').appendTo($('#specifcationContentName3'));
                            }
                        }
                    }
                })
            } else if (data.datas.length == 2) {
                hasSpe = 2;
                $('#specificationName3').show();
                $('#specifcationContentName3').show();
                $('#specificationName4').show();
                $('#specifcationContentName4').show();
                $('#addSpe').hide();
                $('#editSpe').show();
                $.ajax({
                    url: '/crm/specificationC/getSpecificationAndContent.json',
                    dataType: 'json',
                    data: {
                        goodid: $('#idBox').html(),
                    },
                    type: 'post',
                    success: function (data) {
                        if (data.code == 1) {
                            $('<div style="position: relative;width: 165px;"><input class="db_input bigSpe specificationName3" readonly type="text" value="' + data.datas[0].name + '" id="' + data.datas[0].id + '"></div>').appendTo($('#spe_title1'));
                            $('<div style="position: relative;width: 165px;"><input class="db_input bigSpe specificationName4" readonly type="text" value="' + data.datas[1].name + '" id="' + data.datas[0].id + '"></div>').appendTo($('#spe_title2'));
                            for (var b = 0; b < data.datas[0].data.length; b++) {
                                $('<div style="float: left;position: relative;"><input class="db_input" type="text" readonly value="' + data.datas[0].data[b].content + '" id="' + data.datas[0].data[b].id + '"></div>').appendTo($('#specifcationContentName3'));
                            }
                            for (var b = 0; b < data.datas[1].data.length; b++) {
                                $('<div style="float: left;position: relative;"><input class="db_input" type="text" readonly value="' + data.datas[1].data[b].content + '" id="' + data.datas[1].data[b].id + '"></div>').appendTo($('#specifcationContentName4'));
                            }
                        }
                    }
                })
            }
        }
    })
})

var speBigId = '';
var speSmallId = '';
//编辑单个
$('body').on('dblclick', '.db_input', function () {
    $(this).removeAttr('readonly');
    if ($(this).hasClass('bigSpe')) {
        $(this).parent().append('<img class="title_del" src="../static/img/close-spe.png"/>')
        $(this).parent().parent().siblings().find('img').hide();
        speBigId = $(this).attr('id');
        speSmallId = '';
    } else {
        $(this).parent().append('<img class="spe_del" src="../static/img/close-spe.png"/>')
        $(this).parent().parent().siblings().find('img').hide();
        speSmallId = $(this).attr('id');
        speBigId = '';
    }
})
$('body').on('blur', '.db_input', function () {
    $(this).attr('readonly', true);
    if ($(this).hasClass('bigSpe')) {
        speSmallId = '';

    } else {
        speBigId = '';

    }
})

//无效商品
$('body').on('click', '.title_del', function () {
    var setThis = $(this);
    $.ajax({
        url: '/crm/specificationC/updateSpecification.json',
        dataType: 'json',
        data: {
            specificationid: speBigId,
            name: $('#' + speBigId + '').val(),
            isValid: false,
            token: localStorage.getItem('crmtoken')
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                setThis.parent().parent().remove();
                setThis.parent().parent().siblings('.spe_detail').remove();
                alert('删除此规格成功');
            }
            if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            }
            if (data.code == 0) {
                alert(data.msg);
            }
        }
    })
})
//無效單個規格
$('body').on('click', '.spe_del', function () {
    var setThis = $(this);
    $.ajax({
        url: '/crm/specificationContentC/updateSpecificationContent.json',
        dataType: 'json',
        data: {
            specificationContentId: speSmallId,
            content: $('#' + speSmallId + '').val(),
            isValid: false,
            token: localStorage.getItem('crmtoken')
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                setThis.parent().remove();
                alert('删除此规格成功');
            }
            if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            }
            if (data.code == 0) {
                alert(data.msg);
            }
        }
    })
})

//编辑
$('#save4').click(function () {
    if (speSmallId == '') {
        $.ajax({
            url: '/crm/specificationC/updateSpecification.json',
            dataType: 'json',
            data: {
                specificationid: speBigId,
                name: $('#' + speBigId + '').val(),
                isValid: true,
                token: localStorage.getItem('crmtoken')
            },
            type: 'post',
            success: function (data) {
                if (data.code == 1) {
                    alert('修改成功');
                }
            }
        })
    }
    if (speBigId == '') {
        $.ajax({
            url: '/crm/specificationContentC/updateSpecificationContent.json',
            dataType: 'json',
            data: {
                specificationContentId: speSmallId,
                content: $('#' + speSmallId + '').val(),
                isValid: true,
                token: localStorage.getItem('crmtoken')
            },
            type: 'post',
            success: function (data) {
                if (data.code == 1) {
                    alert('修改成功');
                }
            }
        })
    }
})

//添加
$('#save3').click(function () {
    if (hasSpe == 0) {
        $('#specifcationContentName1 input').each(function () {
            sContent1 += $(this).val() + ','
        })
        $('#specifcationContentName2 input').each(function () {
            sContent2 += $(this).val() + ','
        })
    } else if (hasSpe == 1) {
        $('#specifcationContentName1 input').each(function () {
            sContent1 += $(this).val() + ','
        })
        sContent2 = '';
    } else if (hasSpe == 2) {
        sContent1 = '';
        sContent2 = '';
    }

    $.ajax({
        url: '/crm/specificationContentC/addSpecificationAndContent.json',
        dataType: 'json',
        data: {
            token: localStorage.getItem('crmtoken'),
            specificationName1: $('#specificationName1').val(),
            specifcationContentName1: sContent1,
            specificationName2: $('#specificationName2').val(),
            specifcationContentName2: sContent2,
            goodid: $('#idBox').html(),

        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                alert('添加成功');
                $('#myModal6').removeClass('fade in');
                $('#myModal6').addClass('fade');
                $('#myModal6').attr('aria-hidden', true);
                $('#myModal6').css('display', 'none');
                $('.modal-backdrop').css('display', 'none');
            }
            if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            }
            if (data.code == 0) {
                alert(data.msg);
            }
        }
    })
})
$(function () {
    function keyValue(keyValue) {
        var result;
        $.ajax({
            type: 'POST',
            async: false,
            url: '/crm/specificationContentC/keyValue.json?v=' + new Date().getTime(),
            data: {
                keyValue: keyValue

            },
            dataType: "text",   //参数格式为json
            success: function (data) {
                result = data;
            }
        });
        return result;
    }


    /*$.ajax({
        type: 'POST',
        url: '/crm/specificationContentC/getSpecificationContent.json?v=' + new Date().getTime() + '&goodid=1',
        dataType: "text",   //参数格式为json
        success: function (data) {
            data = data.replace("[", "");
            data = data.replace("]", "");
            var myArray = [];
            myArray = data.split("},");
            for (var i = 0; i < myArray.length; i++) {
                var k = myArray[i];
                k = k.replace("{", "");
                k = k.replace("}", "");
                k = k.replace(/\"/g, "");
                var myArray2 = [];
                myArray2 = k.split(",");
                var g;  //规格id
                var o;  //内容id
                var uu = "";//转换后的K结果（尺寸：X，颜色：红色）
                for (var j = 0; j < myArray2.length; j++) {
                    var tt = keyValue(myArray2[j]);
                    uu = uu + tt + ",";
                }
                uu = uu.replace(/,$/, "");
                $('#spicificationZh').append("<option value='" + k + "'>" + uu + "</option>");
            }

        }


    });*/


})
/*
 * sfy添加规格
 * */
$('#ggsubmit').click(function () {
    var ggname = $('#ggname').val();
    if (ggname == undefined || ggname.length == 0) {
        alert("您输入的内容不能为空");

    } else {
        //发送请求添加规格
        $.ajax({
            type: 'POST',
            url: '/crm/specificationC/addSpecification.json?v=' + new Date().getTime(),
            dataType: "json",   //参数格式为json
            data: {
                specificationName: ggname,
                token: localStorage.getItem('crmtoken'),
                goodid: $('#idBox').html()
            },
            success: function (data) {
                if (data.code == 0) {
                    alert(data.msg);
                    $('#ggModal').modal('hide');

                } else if (data.code == -1) {
                    window.parent.location.href = "/crm/login.jsp";
                } else if (data.code == 1) {
                    $('#ggModal').modal('hide');
                    alert("添加成功");
                    /*
                    * sfy刷新规格展示列表
                    * */
                    ggzs();
                }
            }
        });
    }


});

/*
* 规格，规格内容，规格组合显示与隐藏
* */

$('#guigeneirongtitle').click(function () {
    ggnrzs();

});
$('#guigezuhetitle').click(function () {
    $('#spicificationZh').empty();
    /*    $('#inventory2').attr('readonly','readonly');*/
    $.ajax({
        type: 'POST',
        url: '/crm/specificationContentC/getSpecificationContent.json?v=' + new Date().getTime() + '&goodid=' + $('#idBox').html(),
        dataType: "json",   //参数格式为json
        success: function (data) {
            data=JSON.stringify(data);
            data = data.replace("[", "");
            data = data.replace("]", "");
            var myArray = [];
            myArray = data.split("},");
            for (var i = 0; i < myArray.length; i++) {
                var k = myArray[i];
                k = k.replace("{", "");
                k = k.replace("}", "");
                k = k.replace(/\"/g, "");
                var myArray2 = [];
                myArray2 = k.split(",");
                var g;  //规格id
                var o;  //内容id
                var uu = "";//转换后的K结果（尺寸：X，颜色：红色）
                for (var j = 0; j < myArray2.length; j++) {

                    var tt = keyValue(myArray2[j]);
                    // alert("tt:" + tt);

                    uu = uu + tt + ",";


                }
                uu = uu.replace(/,$/, "");
                $('#spicificationZh').append("<option value='" + k + "'>" + uu + "</option>");
            }
            $.ajax({
                url: '/crm/goodSpecificationC/getGoodSpecification.json',
                dataType: 'json',
                data: {
                    goodid: $('#idBox').html(),
                    propertiesid: $('#spicificationZh').val(),
                },
                success: function (data) {

                    if (data.code == 0) {
                        var memberPrice= $('#memberPrice').val();
                        var costPrice= $('#costPrice').val();
                        var ddPrice= $('#ddPrice').val();
                        var purchasePrice= $('#purchasePrice').val();

                        $('#memberPrice2').val(memberPrice);
                        $('#costPrice2').val(costPrice);
                        $('#ddPrice2').val(ddPrice);
                        $('#purchasePrice2').val(purchasePrice);

                        $('#saveGoodsSpecification').show();
                        $('#editGoodsSpecification').hide();
                        $('#integral2').val(null);


                        //$('#createTime2').val(data.createTime);
                        //$('#mainImg2').attr('src', "");
                        $('#integralTips2').html('');
                    }
                    if (data.code == 1) {
                        var data = data.datas;
                        $("#guigezuheid").val(data.id);
                        $('#saveGoodsSpecification').hide();
                        $('#editGoodsSpecification').show();
                        //$('#inventory2').val(data.inventory);
                        //$('#totalInventory2').val(data.totalInventory);
                        /*  $('#inventory2').attr("readonly","readonly")//将input元素设置为readonly
                          $('#totalInventory2').attr("readonly","readonly")//将input元素设置为readonly*/
                        $('#memberPrice2').val(data.memberPrice);
                        $('#costPrice2').val(data.costPrice);
                        $('#ddPrice2').val(data.ddPrice);
                        $('#purchasePrice2').val(data.purchasePrice);
                        $('#parameter2').find('div[contenteditable="true"]').html(data.parameter);
                        //$('#mainImg2').attr('src', data.image);
                        $('#imgBox2').empty();
                        $('#imgBox2').append('<div class="oneImgBox2"><img id="mainImg2" src="'+data.image+'" alt="img" style="width: 66px;height: 66px;"><span class="del">×</span></div>')


                        //$('#createTime2').val(data.createTime);
                        //$('#mainImg2').attr('src', data.image);
                    }
                }
            })

        }
    });


});

// 获取规格组合名称
function keyValue(keyValue) {
    var result;
    $.ajax({
        type: 'POST',
        async: false,
        url: '/crm/specificationContentC/keyValue.json?v=' + new Date().getTime(),
        data: {
            keyValue: keyValue

        },
        dataType: "text",   //参数格式为json
        success: function (data) {
            result = data;
        }
    });
    return result;
}

//展示规格商品 数据
function changeSpecification() {
    $.ajax({
        type: 'POST',
        url: '/crm/goodSpecificationC/getGoodSpecification.json?v=' + new Date().getTime(),
        dataType: 'json',
        data: {
            goodid: $('#idBox').html(),
            propertiesid: $('#spicificationZh').val(),
        },
        success: function (data) {

            if (data.code == 0) {

                $('#saveGoodsSpecification').show();
                $('#editGoodsSpecification').hide();
                $('#inventory2').val(null);
                $('#totalInventory2').val(null);
                // $('#totalInventory2').removeAttr("readonly");//去除input元素的readonly属性
                $('#purchasePrice2').val(null);
                $('#costPrice2').val(null);
                $('#ddPrice2').val(null);
                $('#memberPrice2').val(null);
                $('#integral2').val(null);
                //$('#createTime2').val(data.createTime);
                //$('#mainImg2').attr('src', "");
                $('#integralTips2').html('');
            }
            if (data.code == 1) {
                var data = data.datas;
                /*
                * 保存按钮变成编辑按钮
                * */
                $('#saveGoodsSpecification').hide();
                $('#editGoodsSpecification').show();
                $('#inventory2').val(data.inventory);
                /*   $('#inventory2').attr("readonly","readonly")//将input元素设置为readonly*/
                $('#totalInventory2').val(data.totalInventory);
                /*              $('#totalInventory2').attr("readonly","readonly")//将input元素设置为readonly*/
                $('#purchasePrice2').val(data.purchasePrice);
                $('#costPrice2').val(data.costPrice);
                $('#ddPrice2').val(data.ddPrice);
                $('#memberPrice2').val(data.memberPrice);
                $('#integral2').val(data.integral);
                //$('#createTime2').val(data.createTime);
                $("#guigezuheid").val(data.id);
                $('#parameter2').find('div[contenteditable="true"]').html(data.parameter);
                //$('#mainImg2').attr('src', data.image);
                $('#imgBox2').empty();
                $('#imgBox2').append('<div class="oneImgBox2"><img id="mainImg2" src="'+data.image+'" alt="img" style="width: 66px;height: 66px;"><span class="del">×</span></div>')
            }
        }
    })
}

$(document).on('click','.del',function () {
    $('#mainImg2').attr('src','../static/img/uploadImg.png');
    $(this).parent().empty().hide();
})

//添加规格商品
$('#saveGoodsSpecification').click(function () {
    if($('#mainImg2').attr('src')=='../static/img/uploadImg.png'||$('#mainImg2').attr('src')==''||$('#mainImg2').attr('src')==undefined){
        alert('规格图片不能为空');
        return;
    }
    else if ($('#memberPrice2').val() == null || $('#memberPrice2').val() == undefined || $('#memberPrice2').val() == "") {
        alert("会员价格不能为空");
        return;
    }

    $.ajax({
        type: 'POST',
        url: '/crm/goodSpecificationC/addGoodSpecification.json?v=' + new Date().getTime(),
        dataType: 'json',
        data: {
            token: localStorage.getItem('crmtoken'),
            goodId: $('#idBox').html(),
            propertiesIds: $('#spicificationZh').val(),
            propertiesNames: $('#spicificationZh').find("option:selected").text(),
            image: $('#mainImg2').attr('src'),
            memberPrice: $('#memberPrice2').val(),
            ddPrice: $('#ddPrice2').val(),
            costPrice: $('#costPrice2').val(),
            purchasePrice: $('#purchasePrice2').val(),
            parameter: $('#parameter2').find('div[contenteditable="true"]').html(),
        },
        success: function (data) {

            if (data.code == 0) {
                alert(data.msg);
            }
            if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            }
            if (data.code == 1) {
                alert("添加成功");

            }
        }
    })
})
/*
* sfy
* 更新规格组合相关的内容
* */
$('#editGoodsSpecification').click(function () {
    //if ($('#inventory2').val() == null || $('#inventory2').val() == undefined || $('#inventory2').val() == "") {
    //    alert("库存不能为空");
    //    return;
    //} else
    if($('#mainImg2').attr('src')=='../static/img/uploadImg.png'||$('#mainImg2').attr('src')==''||$('#mainImg2').attr('src')==undefined){
        alert('规格图片不能为空');
        return;
    }
    if ($('#memberPrice2').val() == null || $('#memberPrice2').val() == undefined || $('#memberPrice2').val() == "") {
        alert("会员价格不能为空");
        return;
    }
    //else if ($('#integral2').val() == null || $('#integral2').val() == undefined || $('#integral2').val() == "") {
    //    alert("所增送积分不能为空");
    //    return;
    //}
    $.ajax({
        type: 'POST',
        url: '/crm/goodSpecificationC/updateGoodSpecification.json',
        dataType: 'json',
        data: {
            token: localStorage.getItem('crmtoken'),
            image:  $('#mainImg2').attr('src'),
            memberPrice: $('#memberPrice2').val(),
            purchasePrice: $('#purchasePrice2').val(),
            costPrice: $('#costPrice2').val(),
            ddPrice: $('#ddPrice2').val(),
            parameter: $('#parameter2').find('div[contenteditable="true"]').html(),


            id: $("#guigezuheid").val()
        },
        success: function (data) {

            if (data.code == 0) {
                alert(data.msg);
            }
            if (data.code == 1) {

                alert("更新成功");

            }
        }
    })
})

/*
*sfy 弹出此规格记录值，并将相应的数据铺进去
* */
function aa(a) {
    $.ajax({
        type: 'POST',
        url: '/crm/specificationC/detailsSpecification.json?v=' + new Date().getTime(),
        dataType: "json",   //参数格式为json
        data: {
            id: a.id
        },
        success: function (data) {
            if (data.code == 0) {
                alert(data.msg);
            } else if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            } else if (data.code == 1) {
                /*
                * sfy弹出相应的模态框，并且将请求到的数据扑到模态框中
                * */
                //弹出模态框
                $('#ggbjModal').modal('show');
                $('#ggnamebj').val(data.datas.name);
                $('#ggsubmitbj').val(data.datas.id)
                //根据后台反馈出来的规格状态，进行相应值设置
                "有效" == data.datas.isValid ? $('#ggselect').val(1) : $('#ggselect').val(0);
            }

        }
    });

}

/*
* sfy 将编辑后的规格提交到后台
* */

function ggbjsubmit(a) {
    var flag = true;
    $('#ggselect').val() == 1 ? flag = true : flag = false;


    $.ajax({
        type: 'POST',
        url: '/crm/specificationC/updateSpecification.json?v=' + new Date().getTime(),
        dataType: "json",   //参数格式为json
        data: {
            token: localStorage.getItem('crmtoken'),
            specificationid: a.value,
            name: $('#ggnamebj').val(),
            isValid: flag
        },
        success: function (data) {
            if (data.code == 0) {
                alert(data.msg);
            } else if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            } else if (data.code == 1) {
                $('#ggbjModal').modal('hide');
                alert("修改成功");
                ggzs();
            }

        }
    });

}

/*
 * 点击规格内容title开始铺数据
 * */
function ggnrzs() {

    $.ajax({
        type: 'POST',
        url: '/crm/specificationC/getSpecificationAndContent.json?v=' + new Date().getTime(),
        dataType: "json",   //参数格式为json
        data: {
            goodid: $('#idBox').html()
        },
        success: function (data) {
            if (data.code == 0) {
                alert(data.msg);
            } else if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            } else if (data.code == 1) {
                $('#ggbjnrzs').empty();
                //将商品的规格内容铺进去
                $.each(data.datas, function (index, obj) {
                    //sfy铺规格名称
                    $('#ggbjnrzs').append('<div>');
                    $('#ggbjnrzs').append('<strong><span  style="font-size:20px" >' + obj.name + '</span></strong>&nbsp;&nbsp;');
                    $('#ggbjnrzs').append('<button onclick="ggnraddModal(this)" value="' + obj.id + '" type="button" class="btn btn-success btn-xs">添加</button>');
                    $('#ggbjnrzs').append('</div><br/><br/>');

                    $('#ggbjnrzs').append('<div>');
                    //sfy循环铺规格内容
                    $.each(obj.data, function (index, obj2) {
                        $('#ggbjnrzs').append(' <label style="font-size:18px">' + obj2.content + '</label>');
                        $('#ggbjnrzs').append(' <a id="' + obj2.id + '" onclick="ggnrbjmtk(this)"><span class="glyphicon glyphicon-edit"></span></a>&nbsp;&nbsp;&nbsp;');
                    });
                    $('#ggbjnrzs').append('</div><br/><br/>');

                });
            }

        }
    });

}

/*
* sfy
* 点击规格内容编辑，跳出模态框
* */
function ggnrbjmtk(a) {
    /*规格内容详情，并且铺进去*/
    $.ajax({
        type: 'POST',
        url: '/crm/specificationContentC/detailsSpecificationContent.json?v=' + new Date().getTime(),
        dataType: "json",   //参数格式为json
        data: {
            id: a.id
        },
        success: function (data) {
            if (data.code == 0) {
                alert(data.msg);
            } else if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            } else if (data.code == 1) {
                /*
                 * sfy弹出展示规格内容的模态框
                 * */
                $('#ggnrbjModal').modal('show');
                $('#ggrnnamebj').val(data.datas.content);
                $('#ggnrsubmitbj').val(data.datas.id)
                //根据后台反馈出来的规格状态，进行相应值设置
                "有效" == data.datas.isValid ? $('#ggnrselect').val(1) : $('#ggnrselect').val(0);
            }

        }
    });
}

/*
* sfy
* 编辑内容弹出框，点击提交按钮，进行想应信息的更新
* */
function ggnrbjsubmit(a) {

    var ggnrname = $('#ggrnnamebj').val();

    if (ggnrname == undefined || ggnrname.length == 0) {
        alert("您输入的内容不能为空");

    } else {

        //进行更新规格内容
        var flag = true;
        $('#ggnrselect').val() == 1 ? flag = true : flag = false;

        $.ajax({
            type: 'POST',
            url: '/crm/specificationContentC/updateSpecificationContent.json?v=' + new Date().getTime(),
            dataType: "json",   //参数格式为json
            data: {
                content: $('#ggrnnamebj').val(),
                specificationContentId: a.value,
                token: localStorage.getItem('crmtoken'),
                isValid: flag

            },
            success: function (data) {

                if (data.code == 0) {
                    alert(data.msg);
                    $('#gggnrbjModal').modal('hide');

                } else if (data.code == -1) {
                    window.parent.location.href = "/crm/login.jsp";
                } else if (data.code == 1) {
                    $('#ggnrbjModal').modal('hide');
                    alert("更新成功");
                    /*
                     * sfy刷新规格内容展示列表
                     * */
                    ggnrzs();
                }
            }
        });

    }


}

//点击添加弹出弹出框

function ggnraddModal(a) {
    $('#ggnraddModal').modal('show');
    $('#ggnraddsubmit').val(a.value);
}


/*
* sfy  点击规格内容添加按钮，添加规格内容
* */
function ggnraddsubmit(a) {

    var ggnrname = $('#ggnrname').val();
    if (ggnrname == undefined || ggnrname.length == 0) {
        alert("添加内容不能为空");

    } else {
        $.ajax({
            type: 'POST',
            url: '/crm/specificationContentC/addSpecificationContent.json?v=' + new Date().getTime(),
            dataType: "json",   //参数格式为json
            data: {
                specificatonid: a.value,
                token: localStorage.getItem('crmtoken'),
                specificationContentName: $('#ggnrname').val()

            },
            success: function (data) {

                if (data.code == 0) {
                    alert(data.msg);


                } else if (data.code == -1) {
                    window.parent.location.href = "/crm/login.jsp";
                } else if (data.code == 1) {
                    $('#ggnraddModal').modal('hide');
                    alert("添加成功");
                    /*
                     * sfy刷新规格内容展示列表
                     * */
                    ggnrzs();
                }
            }
        });
    }
}


//增值服务
$('.liList').click(function () {
    $(this).addClass('active');
    $(this).siblings().removeClass('active');
    var divName = $(this).children().attr('showDiv');
    $('#' + divName + '').show();
    $('#' + divName + '').siblings().hide();
    var url = '',
        stateValue = $(this).attr('stateValue');
    if (stateValue == 1) {
        url = '/crm/goodsValueAddedServicesC/getlist.json'
        doZengzhi(url, stateValue, divName);
    } else if (stateValue == 2) {
        url = '/crm/ddmGoodPropertyRelationC/getlist.json'
        doZengzhi(url, stateValue, divName);
    } else if (stateValue == 3) {
        url = '/crm/goodsObligationC/getlist.json'
        doZengzhi(url, stateValue, divName);
    } else if (stateValue == 4) {
        url = '/crm/goodsRelateCategoryC/getGoodsCategory.json';
        doZengzhi(url, stateValue, divName);
    } else if (stateValue == 5) {
        url = '/crm/stagesC/searchGoodsStages.json';
        $('#spicificationZh3').empty();
        $('#spicificationDiv').hide();
        $('#fenqidivid').val(5);
        getFenQi5(url);
    } else if (stateValue == 6) {
        $('#spicificationDiv').show();
        $('#fenqidivid').val(6);
        getFenQiGuiGe();
    }else if (stateValue == 7) {
        url = '/crm/seckillGoodsC/list.json';
        var  goodsSpecificationId='',
            seckillDate='',
            goodsName='',
            abbreviation='',
            state='';
        var  pageNu=1;
        getmiaosha(url,goodsSpecificationId,seckillDate,goodsName,abbreviation,state,pageNu);
        getmiaoshaGuiGe();

    }
})

function getmiaosha(url) {
    $.ajax({
        url: url,
        dataType: 'json',
        data: {
            token: localStorage.getItem('crmtoken'),
            goodsId: $('#idBox').html(),
            pageSize:30,
            pageNu:1,
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                if (data.datas.length > 0) {
                    $('#miaoshatable').empty();
                    for (var i = 0; i < data.datas.length; i++) {
                        $('<tr><td>' + data.datas[i].id + '</td>' +
                            '<td>' + data.datas[i].goodsName + '</td>' +
                            '<td>' + data.datas[i].specificationName + '</td>' +
                            '<td>' + data.datas[i].seckillDate + '</td>' +
                            '<td>' + data.datas[i].salePrice + '</td>' +
                            '<td>' + data.datas[i].seckillPrice + '</td>' +
                            '<td>' + data.datas[i].state + '</td>' +
                            '<td>' + data.datas[i].totalInventory + '</td>' +
                            '<td>' + data.datas[i].inventory + '</td>' +
                            '<td>' + data.datas[i].saleVolume + '</td></tr>').appendTo($('#miaoshatable'));

                    }

                }
            }
        }
    })
}

function getmiaoshaGuiGe() {
    $('#spicificationZh6').empty();
    $.ajax({
        type: 'POST',
        url: '/crm/goodSpecificationC/getGoodSpecificationAll2.json?v=' + new Date().getTime() + '&goodid=' + $('#idBox').html(),
        dataType: "json",   //参数格式为json
        success: function (data) {
            if(data.datas.length>0){
                for (var i = 0; i < data.datas.length; i++) {

                    $('#spicificationZh6').append("<option value='" +data.datas[i].id + "'>" +data.datas[i].name+ "</option>");

                }
            }

        }
    })

}

$('#miaoshaAdd').click(function () {
    $.ajax({
        url:'/crm/seckillGoodsC/add.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            goodsId:$('#idBox').html(),
            goodsSpecificationId:$('#spicificationZh6').val(),
            inventory:$('#inventory').val(),
            seckillPrice:$('#seckillPrice').val(),
            seckillDate:$('#seckillDate').val(),
        },
        type:'post',
        success:function (data) {

            if(data.code==1){
                alert('添加成功');
                $('#miaoshaModa').modal('hide');
                $('#miaoshaModa').removeClass('fade in');
                $('#miaoshaModa').addClass('fade');
                $('#miaoshaModa').attr('aria-hidden',true);
                $('#miaoshaModa').css('display','none');
                $('.modal-backdrop').css('display','none');
                $('#miaoshaModa input').val('');

                url = '/crm/seckillGoodsC/list.json';
                getmiaosha(url);
                getmiaoshaGuiGe();

            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==0){
                alert(data.msg);
            }
        }
    })
})

function getFenQi5(url) {
    $.ajax({
        url: url,
        dataType: 'json',
        data: {
            token: localStorage.getItem('crmtoken'),
            goodsId: $('#idBox').html(),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                if (data.datas.length > 0) {
                    $('#fenqitable').empty();
                    for (var i = 0; i < data.datas.length; i++) {
                        $('<tr><td>' + data.datas[i].id + '</td>' +
                            '<td>' + data.datas[i].goodsName + '</td>' +
                            '<td>' + data.datas[i].instalmentAmount + '</td>' +
                            '<td>' + data.datas[i].prepayment + '</td>' +
                            '<td>' + data.datas[i].periods + '</td>' +
                            '<td>' + data.datas[i].state + '</td>' +
                            '<td>' + data.datas[i].createUserName + '</td>' +
                            '<td>' + data.datas[i].createTime + '</td>' +
                            '<td class="mdFenQi" style="text-decoration: underline;cursor: pointer;" fenqiId="'+data.datas[i].id+'" goodsName="' + data.datas[i].goodsName + '" prepayment="' + data.datas[i].prepayment + '" periods="' + data.datas[i].periods + '" instalmentAmount="' + data.datas[i].instalmentAmount + '" fenqiState="' + data.datas[i].state + '">编辑</td></tr>').appendTo($('#fenqitable'));

                    }
                    $('.mdFenQi').click(function(){
                        fenqiId = $(this).attr('fenqiId');
                        goodsName= $(this).attr('goodsName');
                        prepayment= $(this).attr('prepayment');
                        periods= $(this).attr('periods');
                        instalmentAmount= $(this).attr('instalmentAmount');
                        fenqiState=$(this).attr('fenqiState');
                        $('#specificationName').val('');
                        $('#prepayment1').val('');
                        $('#periods1').val('');
                        $('#instalmentAmount1').val('');
                        $('#specificationName').val('');
                        $('#goodsName').val('');
                        $('#specificationNamediv').hide();

                        $('#fenqidivid').val(5);
                        $('#goodsName').val(goodsName);
                        $('#prepayment1').val(prepayment);
                        $('#periods1').val(periods);
                        $('#instalmentAmount1').val(instalmentAmount);
                        $('#fenqiId').val(fenqiId);
                        if(fenqiState=='有效'){
                            $('#fenqiState').val('1')
                        }
                        if(fenqiState=='无效效'){
                            $('#fenqiState').val('0')
                        }

                        $('#goodsNamediv').show();
                        $('#bjFenQiModal').modal('show');

                    })

                }
            }
        }
    })
}



$('#fenqiAdd').click(function () {
    var  fenqidivid=$('#fenqidivid').val();
    $.ajax({
        url:'/crm/stagesC/addStages.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            goodId:$('#idBox').html(),
            propertiesIds:$('#spicificationZh3').val(),
            prepayment:$('#prepayment').val(),
            periods:$('#periods').val(),
            instalmentAmount:$('#instalmentAmount').val(),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                alert('添加成功');
                $('#fenqiModa5').modal('hide');
                $('#fenqiModa5').removeClass('fade in');
                $('#fenqiModa5').addClass('fade');
                $('#fenqiModa5').attr('aria-hidden',true);
                $('#fenqiModa5').css('display','none');
                $('.modal-backdrop').css('display','none');
                $('#fenqiModa5 input').val('');

                if(fenqidivid==5){
                    url = '/crm/stagesC/searchGoodsStages.json';
                    $('#spicificationZh3').empty();
                    $('#spicificationDiv').hide();
                    getFenQi5(url);
                }
                if(fenqidivid==6){
                    $('#spicificationDiv').show();
                    getGuiGeFenQi()
                }

            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==0){
                alert(data.msg);
            }
        }
    })
})



function getFenQiGuiGe() {
    $('#spicificationZh2').empty();
    $('#spicificationZh3').empty();
    $.ajax({
        type: 'POST',
        url: '/crm/specificationContentC/getSpecificationContent.json?v=' + new Date().getTime() + '&goodid=' + $('#idBox').html(),
        dataType: "json",   //参数格式为json
        success: function (data) {
            data=JSON.stringify(data);
            data = data.replace("[", "");
            data = data.replace("]", "");
            var myArray = [];
            myArray = data.split("},");
            for (var i = 0; i < myArray.length; i++) {
                var k = myArray[i];
                k = k.replace("{", "");
                k = k.replace("}", "");
                k = k.replace(/\"/g, "");
                var myArray2 = [];
                myArray2 = k.split(",");
                var g;  //规格id
                var o;  //内容id
                var uu = "";//转换后的K结果（尺寸：X，颜色：红色）
                for (var j = 0; j < myArray2.length; j++) {

                    var tt = keyValue(myArray2[j]);
                    // alert("tt:" + tt);
                    uu = uu + tt + ",";
                }
                uu = uu.replace(/,$/, "");
                $('#spicificationZh2').append("<option value='" + k + "'>" + uu + "</option>");
                $('#spicificationZh3').append("<option value='" + k + "'>" + uu + "</option>");

            }
            getGuiGeFenQi()
        }
    })

}
function getGuiGeFenQi() {
    $.ajax({
        url: '/crm/stagesC/searchPropertiesStages.json?',
        dataType: 'json',
        data: {
            token: localStorage.getItem('crmtoken'),
            goodsId: $('#idBox').html(),
            propertiesIds:$('#spicificationZh2').val(),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                if (data.datas.length > 0) {
                    $('#guigefenqitable').empty();
                    for (var i = 0; i < data.datas.length; i++) {
                        $('<tr><td>' + data.datas[i].id + '</td>' +
                            '<td>' + data.datas[i].specificationName + '</td>' +
                            '<td>' + data.datas[i].instalmentAmount + '</td>' +
                            '<td>' + data.datas[i].prepayment + '</td>' +
                            '<td>' + data.datas[i].periods + '</td>' +
                            '<td>' + data.datas[i].state + '</td>' +
                            '<td>' + data.datas[i].createUserName + '</td>' +
                            '<td>' + data.datas[i].createTime + '</td>' +
                            '<td class="mdFenQi" style="text-decoration: underline;cursor: pointer;" fenqiId="'+data.datas[i].id+'" specificationName="' + data.datas[i].specificationName + '" prepayment="' + data.datas[i].prepayment + '" periods="' + data.datas[i].periods + '" instalmentAmount="' + data.datas[i].instalmentAmount + '" fenqiState="' + data.datas[i].state + '">编辑</td></tr>').appendTo($('#guigefenqitable'));
                    }

                    $('.mdFenQi').click(function(){
                        fenqiId = $(this).attr('fenqiId');
                        specificationName= $(this).attr('specificationName');
                        prepayment= $(this).attr('prepayment');
                        periods= $(this).attr('periods');
                        instalmentAmount= $(this).attr('instalmentAmount');
                        fenqiState=$(this).attr('fenqiState');
                        $('#specificationName').val('');
                        $('#prepayment1').val('');
                        $('#periods1').val('');
                        $('#instalmentAmount1').val('');
                        $('#goodsName').val('');
                        $('#goodsNamediv').hide();


                        $('#fenqidivid').val(6);
                        $('#specificationName').val(specificationName);
                        $('#prepayment1').val(prepayment);
                        $('#periods1').val(periods);
                        $('#instalmentAmount1').val(instalmentAmount);
                        $('#specificationNamediv').show();
                        $('#fenqiId').val(fenqiId);
                        if(fenqiState=='有效'){
                            $('#fenqiState').val('1')
                        }
                        if(fenqiState=='无效'){
                            $('#fenqiState').val('0')
                        }
                        $('#bjFenQiModal').modal('show');
                    })

                }
            }
        }
    })
}


function doZengzhi(url, value, name) {
    $.ajax({
        url: url,
        dataType: 'json',
        data: {
            token: localStorage.getItem('crmtoken'),
            goodsId: $('#idBox').html(),
        },
        type: 'post',
        success: function (data) {

            if (data.code == 1) {
                if (data.datas.length > 0) {
                    $('#' + name + '').find('.commonTable').empty();
                    if (value == 1) {
                        for (var i = 0; i < data.datas.length; i++) {
                            $('<tr><td>' + data.datas[i].id + '</td>' +
                                '<td>' + data.datas[i].name + '</td>' +
                                '<td>' + data.datas[i].price + '</td>' +
                                '<td>' + data.datas[i].warrantyPeriod + '</td>' +
                                '<td delValue="'+value+'" class="delItem" delId="'+data.datas[i].id+'">删除</td></tr>').appendTo($('#' + name + '').find('.commonTable'));
                        }
                    }else if (value == 2||value == 3) {
                        for (var i = 0; i < data.datas.length; i++) {
                            $('<tr><td>' + data.datas[i].id + '</td>' +
                                '<td>' + data.datas[i].name + '</td>' +
                                '<td delValue="'+value+'" class="delItem" delId="'+data.datas[i].id+'">删除</td>'+
                                '</tr>').appendTo($('#' + name + '').find('.commonTable'));
                        }
                    }else if (value == 4) {
                        for (var i = 0; i < data.datas.length; i++) {
                            $('<tr><td>' + data.datas[i].id + '</td>' +
                                '<td>' + data.datas[i].firstName + '</td>' +
                                '<td>' + data.datas[i].secondName + '</td>' +
                                '<td>' + data.datas[i].thirdName + '</td>' +
                                '<td delValue="'+value+'" class="delItem" delId="'+data.datas[i].id+'">删除</td>'+
                                '</tr>').appendTo($('#' + name + '').find('.commonTable'));
                        }

                    }
                }
            }
        }
    })
}




$('#fenqiMd').click(function(){
    var  fenqidivid=$('#fenqidivid').val();
    $.ajax({
        url:'/crm/stagesC/updateStages.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            id:fenqiId,
            prepayment:$('#prepayment1').val(),
            periods:$('#periods1').val(),
            instalmentAmount:$('#instalmentAmount1').val(),
            state:$('#fenqiState').val(),

        },
        type:'post',
        success:function(data){
            if(data.code==0){
                alert(data.msg)
                return;
            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==1){
                alert('修改成功');
                $('#bjFenQiModal').removeClass('fade in');
                $('#bjFenQiModal').addClass('fade');
                $('#bjFenQiModal').attr('aria-hidden',true);
                $('#bjFenQiModal').css('display','none');
                $('.modal-backdrop').css('display','none');
                $('#bjFenQiModal input').val('');
                if(fenqidivid==5){
                    url = '/crm/stagesC/searchGoodsStages.json';
                    $('#spicificationZh3').empty();
                    $('#spicificationDiv').hide();
                    getFenQi5(url);
                }
                if(fenqidivid==6){
                $('#spicificationDiv').show();
                    getGuiGeFenQi()
                }
            }
        }
    })
})

$(document).on('click','.delItem',function () {
    $(this).unbind('click');
    var delValue = $(this).attr('delValue'),
        id = $(this).attr('delId');
        doDele(delValue,id);
})



//删除增值服务等
function doDele(value,id) {
    var r=confirm("确定要删除此项吗");
    if (r==true)
    {
        var url ='';
        var name = '';
        var delUrl = '';
        if(value==1){
            delUrl = '/crm/goodsValueAddedServicesC/delete.json';
            name='zengzhifuwumianban';
            url = '/crm/goodsValueAddedServicesC/getlist.json'
        }else if(value==2){
            delUrl = '/crm/ddmGoodPropertyRelationC/delete.json';
            name='shuxingmianban';
            url = '/crm/ddmGoodPropertyRelationC/getlist.json'
        }else if(value==3){
            delUrl = '/crm/goodsObligationC/delete.json';
            name='chengnuomianban';
            url = '/crm/goodsObligationC/getlist.json'
        }else if(value==4){
            delUrl = '/crm/goodsRelateCategoryC/setNotValid.json';
            name='fenleimianban';
            url = '/crm/goodsRelateCategoryC/getGoodsCategory.json';
        }
        $.ajax({
            url:delUrl,
            dataType:'json',
            data:{
                token:localStorage.getItem('crmtoken'),
                id:id,
            },
            type:'post',
            success:function (data) {
                if(data.code==1){
                    alert('删除成功');
                    doZengzhi(url,value,name);
                }
                if(data.code==-1){
                    window.parent.location.href="/crm/login.jsp"
                }
                if(data.code==0){
                    alert(data.msg);
                }
            }
        })
    }
    else{}
}



//添加增值服务
$('#valueAddedServicesKind').change(function () {
    $('#zengzhiName').empty();
    $.ajax({
        url:'/crm/valueAddedServicesC/getValueAddedServices.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('token'),
            valueAddedServicesKindValue: $('#valueAddedServicesKind').val(),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                for(var a=0;a<data.datas.length;a++){
                    $('<option value="'+data.datas[a].id+'">'+data.datas[a].name+' (￥'+data.datas[a].price+') </option>').appendTo($('#zengzhiName'))
                }
            }
        }
    })
})
$('#zengzhiAdd').click(function () {
    $.ajax({
        url:'/crm/goodsValueAddedServicesC/add.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            goodsId:$('#idBox').html(),
            valueAddedServicesId:$('#zengzhiName').val(),
            warrantyPeriod:$('#zengzhiTime').val(),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                alert('添加成功');
                $('#zengzhiModal').modal('hide');
                doZengzhi('/crm/goodsValueAddedServicesC/getlist.json', 1, 'zengzhifuwumianban')
            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==0){
                alert(data.msg);
            }
        }
    })
})

//添加承诺
$('#addChengnuo').click(function () {
    doChengnuo();
})
function doChengnuo() {
    $('#chengnuoBox').empty();
    $.ajax({
        url:'/crm/ddmObligationC/getDdmObligation.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('token'),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                for(var a=0;a<data.datas.length;a++){
                    $('<label>'+data.datas[a].name+'</label><input name="checkbox" value="'+data.datas[a].id+'" class="checkBox" type="checkbox">').appendTo($('#chengnuoBox'))
                }
            }
        }
    })
}
$('#chengnuoAdd').click(function () {
    var str="";
    $("input[name='checkbox']:checked").each(function(){
        str+=$(this).val()+",";
    })
    $.ajax({
        url:'/crm/goodsObligationC/add.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            goodsId:$('#idBox').html(),
            ddmObligationIds:str,
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                alert('添加成功');
                $('#chengnuoModal').modal('hide');
                doZengzhi('/crm/goodsObligationC/getlist.json', 3, 'chengnuomianban')
                //doChengnuo();
            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==0){
                alert(data.msg);
            }
        }
    })
})




//添加属性
$('#addShuxing').click(function () {
    doShuxing();
})
function doShuxing() {
    $('#shuxingBox').empty();
    $.ajax({
        url:'/crm/ddmGoodPropertyC/getAllGoodPropertyName2.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('token'),
            goodsId:$('#idBox').html(),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                for(var a=0;a<data.datas.length;a++){
                    if(data.datas[a].ifShow){
                        $('<label>'+data.datas[a].name+'</label><input class="checkBox" name="checkbox2" value="'+data.datas[a].id+'" type="checkbox" checked>').appendTo($('#shuxingBox'))
                    }else{
                        $('<label>'+data.datas[a].name+'</label><input class="checkBox" name="checkbox2" value="'+data.datas[a].id+'" type="checkbox">').appendTo($('#shuxingBox'))
                    }
                }
            }
        }
    })
}
$('#shuxingAdd').click(function () {
    var str="";
    $("input[name='checkbox2']:checked").each(function(){
        str+=$(this).val()+",";
    })
    $.ajax({
        url:'/crm/ddmGoodPropertyRelationC/add.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            goodsId:$('#idBox').html(),
            propertyIds:str,
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                alert('添加成功');
                $('#shuxingModal').modal('hide');
                doZengzhi('/crm/ddmGoodPropertyRelationC/getlist.json', 2, 'shuxingmianban');
                //doShuxing();
            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==0){
                alert(data.msg);
            }
        }
    })
})

//添加分类
$('#addFenlei').click(function () {
    doFenlei();
})
function doFenlei(){
    $('#yijifenlei').empty();
    $.ajax({
        url:'/crm/goodsCategoryC/firstLevel.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('token'),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                $('#yijifenlei').empty();
                $('<option>请选择一级分类</option>').appendTo($('#yijifenlei'))
                for(var a=0;a<data.datas.length;a++){
                    $('<option value="'+data.datas[a].id+'">'+data.datas[a].name+'</option>').appendTo($('#yijifenlei'))
                }
            }
            $('#yijifenlei').change(function () {
                $.ajax({
                    url:'/crm/goodsCategoryC/secondLevel.json',
                    dataType:'json',
                    data:{
                        parentCategoryId:$('#yijifenlei').val(),
                    },
                    type:'post',
                    success:function (data) {
                        if (data.code == 1) {
                            $('#erjifenlei').empty();
                            $('#erjifenlei').show();
                            $('<option>请选择二级分类</option>').appendTo($('#erjifenlei'))
                            for (var b = 0; b < data.datas.length; b++) {
                                $('<option value="'+data.datas[b].id+'">' + data.datas[b].name + '</option>').appendTo($('#erjifenlei'))
                            }
                        }
                    }
                })
            })
            $('#erjifenlei').change(function () {
                $.ajax({
                    url:'/crm/goodsCategoryC/secondLevel.json',
                    dataType:'json',
                    data:{
                         parentCategoryId:$('#erjifenlei').val(),
                    },
                    type:'post',
                    success:function (data) {
                        if (data.code == 1) {
                            $('#sanjifenlei').empty();
                            $('#sanjifenlei').show();
                            $('<option>请选择三级分类</option>').appendTo($('#sanjifenlei'))
                            for (var c = 0; c < data.datas.length; c++) {
                                $('<option value="'+data.datas[c].id+'">' + data.datas[c].name + '</option>').appendTo($('#sanjifenlei'))
                            }
                        }
                    }
                })

            })
        }
    })
}
$('#fenleiAdd').click(function () {

    $.ajax({
        url:'/crm/goodsRelateCategoryC/add.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            levelOneId:$('#yijifenlei').val(),
            levelTwoId:$('#erjifenlei').val(),
            levelThreeId:$('#sanjifenlei').val(),
            goodsId:$('#idBox').html(),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                alert('添加成功');
                $('#fenleiModal').modal('hide');
                doZengzhi('/crm/goodsRelateCategoryC/getGoodsCategory.json', 4, 'fenleimianban');
                //doFenlei();
            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==0){
                alert(data.msg);
            }
        }
    })
})

//上传主图
var mainImg;
$('#avatarInput').on('change', function(e) {
    var filemaxsize = 1024 * 5;//5M
    var target = $(e.target);
    var Size = target[0].files[0].size / 1024;
    if(Size > filemaxsize) {
        alert('图片过大，请重新选择!');
        $(".avatar-wrapper").childre().remove;
        return false;
    }
    if(!this.files[0].type.match(/image.*/)) {
        alert('请选择正确的图片!')
    } else {
        var filename = document.querySelector("#avatar-name");
        var texts = document.querySelector("#avatarInput").value;
        var teststr = texts; //你这里的路径写错了
        testend = teststr.match(/[^\\]+\.[^\(]+/i); //直接完整文件名的
        filename.innerHTML = testend;
    }

});



$(".avatar-save").on("click", function() {
    var img_lg = document.getElementById('imageHead');
    // 截图小的显示框内的内容
    html2canvas(img_lg, {
        allowTaint: true,
        taintTest: false,
        onrendered: function(canvas) {
            canvas.id = "mycanvas";
            //生成base64图片数据
            var dataUrl = canvas.toDataURL("image/jpeg");
            var newImg = document.createElement("img");
            newImg.src = dataUrl;
            imagesAjax(dataUrl)
        }
    });
})

function imagesAjax(src) {
    var data = {};
    data.img = src;
    data.jid = $('#jid').val();
    mainImg = src;

    $.ajax({
        url:'/crm/image/uploadImage.json',
        data:{
            filed:mainImg,
        },
        dataType:'json',
        type:'post',
        success:function(data){
            if(data.code==1){
                $('#mainImg,#mainImg2').show();
                $('#mainImg,#mainImg2').attr('src',data.datas.path);
                $('#update,#update2').html('更换')
            }
        }
    })
}
$('#update2').click(function () {
    ifSpeImg = 'true';
    $('#imageHead').css({'width':'230px','height':'230px'});
})
$('#update').click(function () {
    ifSpeImg = 'false';
    $('#imageHead').css({'width':'750px','height':'750px'});
})

//保存修改
$('#save').click(function(){
    if($('#avatar-name').html()==""){
        alert('请选择图片');
    }else{
        $('#save').attr('data-dismiss','modal')
    }
})


//上架
$('#shangjia').click(function () {
    $.ajax({
        url:'/crm/ddmGoodsC/updateState.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            id:$('#idBox').html(),
            state:'true',
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                alert('上架成功');
                getCrmDetails($('#idBox').html())
            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==0){
                alert(data.msg);
            }
        }
    })
})

//下架
$('#xiajia').click(function () {
    $.ajax({
        url:'/crm/ddmGoodsC/updateState.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            id:$('#idBox').html(),
            state:'false',
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                alert('下架成功');
                getCrmDetails($('#idBox').html())
            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==0){
                alert(data.msg);
            }
        }
    })
})

